import { defineStore } from "pinia";
import { store } from "@/store";
import { routerArrays } from "@/layout/types";
import { router, resetRouter } from "@/router";
import { storageSession } from "@pureadmin/utils";
import {
  getUserPermissions,
  getInfo,
  login,
  logout,
  getcaptchaImage
} from "@/api/auth";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import type { UserInfoType } from "./types";
import Cookies from "js-cookie";
import { message } from "@/utils/message";
import { set } from "nprogress";

interface IUserStore {
  currentUser: UserInfoType;
  accessToken: string;
}
const CURRENT_USER = "current-user";
const ACCESS_TOKEN = "access-token";
export const useUserStore = defineStore({
  id: "pure-user",
  state: (): IUserStore => ({
    currentUser: storageSession().getItem<UserInfoType>(CURRENT_USER),
    accessToken: storageSession().getItem<string>(ACCESS_TOKEN)
  }),
  getters: {
    getToken(): string {
      return this.accessToken;
    },
    getCurrentUser(): UserInfoType {
      return this.currentUser;
    }
  },
  actions: {
    setToken(accessToken: string) {
      this.accessToken = accessToken;
      storageSession().setItem(ACCESS_TOKEN, accessToken);
    },
    setCurrentUser(currentUser: UserInfoType) {
      this.currentUser = currentUser;
      storageSession().setItem(CURRENT_USER, currentUser);
    },
    /** 登入 */
    async login(data: any) {
      const user = await login(data);
      console.log(user, "user");
      if (user.code == 200) {
        message(user?.message || "登录成功", { type: "success" });
        this.setToken(user.data.token);
        Cookies.set("Admin-Token", user.data.token);
        // const permissions = await getUserPermissions();
        // user.permissions = permissions ?? [];
        const userdata = await getInfo();
        console.log(userdata, "userdata");
        this.setCurrentUser(userdata.data);
        const currentUser = useUserStoreHook().getCurrentUser;
        user.permissions = currentUser.roles ?? [];
        return Promise.resolve(user);
      } else if (user.code == 500) {
        // return Promise.resolve(user);
        // message(user?.message || "登录失败", { type: "error" });
      } else {
        return Promise.reject("登陆失败");
      }
    },
    /** 退出登录 */
    async logOut(data: any) {
      if (data?.type == 1) {
        this.currentUser = null;
        this.accessToken = null;
        storageSession().setItem(ACCESS_TOKEN, null);
        storageSession().setItem(CURRENT_USER, null);
        useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
        resetRouter();
        message("2s后自动退出到登录页", { type: "success" });
        setTimeout(() => {
          router.push("/login");
        }, 2000);
        message("退出成功", { type: "success" });
      } else {
        const res: any = await logout();
        if (res.code === 200) {
          this.currentUser = null;
          this.accessToken = null;
          storageSession().setItem(ACCESS_TOKEN, null);
          storageSession().setItem(CURRENT_USER, null);
          useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
          resetRouter();
          router.push("/login");
        } else {
          console.error("登出失败:");
          return Promise.reject("登出失败");
        }
      }
    },
    // 获取登录图片验证码
    async getimg() {
      const imgdata = await getcaptchaImage();
      return Promise.resolve(imgdata);
    }
  }
});

export function useUserStoreHook() {
  return useUserStore(store);
}
